import { useEffect, useId, useMemo, useRef, useState } from 'react'
import type { FC } from 'react'

import { produce } from 'immer'
import { Form, Input, Modal } from 'antd'
import Education from '../education/edit'
import Project from '../project/edit'
import Work from '../work/edit'
import School from '../school/edit'
import Certificate from '../certificate/edit'
import Hobby from '../hobby/edit'
import Skills from '../skills/edit'
import Internship from '../internship/edit'
import Custom from '../custom/edit'
import Selfevaluation from '../selfevaluation/edit'
import contentStyle from '../../index.module.scss'
import BottomButton from '../../components/bottomButton'
import styles from './index.module.scss'
import notification from '@/app/components/hooks/useNotification'
import { getInitContent } from '@/app/utils'
import { useContentStore, useServerStore, useStore } from '@/store'
import Confirm from '@/app/components/Confirm'

interface IndexProps {
  type: Sections
  onChangeCurrent?: () => void
}

const Index: FC<IndexProps> = ({ type, onChangeCurrent, ...props }) => {
  const { updateSection, addContent, deleteContent, content } = useContentStore(state => state, (o, n) => {
    return o.content[type] === n.content[type]
  })
  const key = useId()
  const [loading, setLoading] = useState(false)
  const serverStore = useServerStore()
  const { index, setCurrentTab, isMobile } = useStore()
  const data = content[type]
  const oldFormData = useRef<any>(null)
  const [form] = Form.useForm()
  useEffect(() => {
    form.setFieldsValue(data?.entries?.[index] || {})
    if (data?.entries?.[index]) {
      oldFormData.current = data?.entries?.[index]
    }
    if (!data) {
      addContent(getInitContent(type), type)
    }
  }, [])
  const reset = () => {
    let isDelete = false
    const d = produce(content, (draft) => {
      if (draft) {
        if (Object.keys(oldFormData.current || {}).length) {
          draft[type].entries[index] = oldFormData.current
        }
        else {
          draft[type].entries = draft[type].entries.filter((_, i) => i < index)
        }
        if (draft[type].entries.length === 0 && !oldFormData.current) {
          isDelete = true
          delete draft[type]
        }
      }
    })
    if (isDelete) {
      deleteContent(type)
    }
    else {
      updateSection(d[type], type)
    }
  }
  const clearDate = (dateObj) => {
    if (dateObj?.startDate) {
      if (!dateObj.startDate.year) {
        delete dateObj.startDate.year
      }
      if (!dateObj.startDate.month) {
        delete dateObj.startDate.month
      }
    }
    if (dateObj?.endDate) {
      if (!dateObj.endDate.year) {
        delete dateObj.endDate.year
      }
      if (!dateObj.endDate.month) {
        delete dateObj.endDate.month
      }
      if (!dateObj.endDate.untilToday) {
        delete dateObj.endDate.untilToday
      }
    }
    if (!Object.keys(dateObj?.startDate || {}).length) {
      dateObj.startDate = null
    }
    if (!Object.keys(dateObj?.endDate || {}).length) {
      dateObj.endDate = null
    }
  }
  return <div className={styles.contentItemEdit}>

    <Form className={contentStyle.card} layout="vertical" form={form} onValuesChange={(value, values) => {
      if (value.description && value.description === data?.entries?.[index]?.description) {
        return
      }
      clearDate(values)
      updateSection(produce(content[type], (draft) => {
        if (draft) {
          if (!values.key && !values.id) {
            values.key = key
          }
          draft.entries[index] = values
        }
      }), type)
    }}>
      {
        type === 'education' ? <Education displayName={data?.displayName}></Education> : null
      }
      {
        type === 'project' ? <Project displayName={data?.displayName} ></Project> : null
      }
      {
        type === 'work' ? <Work displayName={data?.displayName} ></Work> : null
      }
      {
        type === 'certificate' ? <Certificate displayName={data?.displayName}></Certificate> : null
      }
      {
        type === 'skills' ? <Skills displayName={data?.displayName}></Skills> : null
      }
      {
        type === 'school' ? <School displayName={data?.displayName}></School> : null
      }
      {
        type === 'internship' ? <Internship displayName={data?.displayName}></Internship> : null
      }
      {
        type === 'selfevaluation' ? <Selfevaluation displayName={data?.displayName}></Selfevaluation> : null
      }
      {
        type === 'custom' ? <Custom {...props} displayName={data?.displayName}></Custom> : null
      }
      {
        type === 'hobby' ? <Hobby {...props} displayName={data?.displayName}></Hobby> : null
      }

      <Form.Item name={'id'} hidden>
        <Input></Input>
      </Form.Item>
      <Form.Item name={'key'} hidden>
        <Input></Input>
      </Form.Item>
      <Form.Item name={'isHidden'} hidden>
        <Input></Input>
      </Form.Item>
      <Form.Item name={'contentId'} hidden>
        <Input></Input>
      </Form.Item>
    </Form>

    <BottomButton loading={loading} onCancel={() => {
      reset()
      setCurrentTab('content')
    }}
    onDelete={async () => {
      if (isMobile) {
        Confirm({
          content: '确认删除该条数据？',
          onOk: async () => {
            if (content[type]) {
              const formData = await form.getFieldsValue()
              await serverStore.delEntry(formData, content[type])
            }
          },
        })
      }
      else {
        Modal.confirm({
          content: '确认删除该条数据？',
          okText: '确认',
          title: '提示',
          cancelText: '取消',
          onOk: async () => {
            if (content[type]) {
              const formData = await form.getFieldsValue()
              await serverStore.delEntry(formData, content[type])
            }
          },
        })
      }
    }}
    onConfirm={async () => {
      setCurrentTab('content')
    }} />
  </div>
}

export default (Index)
